import os
import sys
from pathlib import Path
from dotenv import load_dotenv

def get_project_root() -> Path:
    """
    向上查找，直到找到包含 .env 文件或 .git 文件夹的项目根目录。
    """
    current_path = Path.cwd()
    while current_path != current_path.parent:
        if (current_path / ".env").exists() or \
                (current_path / ".git").exists() or \
                (current_path / "src").exists():
            return current_path
        current_path = current_path.parent
    raise FileNotFoundError("Could not find the project root. Make sure a .env or .git folder exists.")

# --- 自动执行 ---
PROJECT_ROOT = get_project_root()

# 将项目根目录添加到 Python 路径中
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

dotenv_path = PROJECT_ROOT / '.env'
load_dotenv(dotenv_path=dotenv_path)

# --- 提供全局路径常量 ---
CONFIG_PATH = PROJECT_ROOT / os.getenv("CONFIG_PATH", "config.yaml")
DATABASE_PATH = PROJECT_ROOT / os.getenv("DATABASE_PATH", "data/db/fingerprints.db")
SCHEMA_PATH = PROJECT_ROOT / os.getenv("SCHEMA_PATH", "data/db/schema.sql")
MUSIC_LIBRARY_PATH = PROJECT_ROOT / os.getenv("MUSIC_LIBRARY_PATH", "data/music_library")
PROCESSOR_RESULTS_PATH = PROJECT_ROOT / os.getenv('PROCESSOR_RESULTS_PATH', 'data/processor_result')
TEST_DATA_PATH = PROJECT_ROOT / os.getenv("TEST_DATA_PATH", "data/test_data")

# 主结果文件路径，总是指向最新一次测试
BATCH_RESULTS_PATH = PROJECT_ROOT / os.getenv("BATCH_RESULTS_PATH", "data/batch_results.json")
# 历史测试报告存档目录
BATCH_HISTORY_PATH = PROJECT_ROOT / os.getenv("BATCH_HISTORY_PATH", "data/batch_history")
